import { _decorator, Component, resources, SpriteFrame } from 'cc'
const { ccclass } = _decorator
import { createUINode, randomByRange } from '../../utils'
import { TileManager } from './TileManager'
import DataManager from '../../Runtime/DataManager'
import ResourceManager from '../../Runtime/ResourceManager'

@ccclass('TileMapManager')
export class TileMapManager extends Component {
  async init() {
    const spriteFrames = await ResourceManager.Instance.loadDir('texture/tile/tile')

    // 从数据中心获取地图信息
    const { mapInfo } = DataManager.Instance

    DataManager.Instance.tileInfo = []

    for (let i = 0; i < mapInfo.length; i++) {
      const column = mapInfo[i]
      DataManager.Instance.tileInfo[i] = []
      for (let j = 0; j < column.length; j++) {
        const item = column[j]

        if (item.src === null || item.type === null) continue

        let number = item.src

        if ((number === 1 || number === 5 || number === 9) && i % 2 === 0 && j % 2 === 0) {
          number += randomByRange(0, 4)
        }

        const imgSrc = `tile (${number})`

        const node = createUINode()
        const spriteFrame = spriteFrames.find(spriteFrame => spriteFrame.name === imgSrc)

        const tileManager = node.addComponent(TileManager)
        DataManager.Instance.tileInfo[i][j] = tileManager // 保存到数据中心
        const type = item.type
        tileManager.init(type,spriteFrame, i, j)
        node.setParent(this.node)
      }
    }
  }
}
